<?php

namespace Home\Controller;
use Think\Controller;
class PacketController extends BaseController{
    
    /**
     * @desc 拒收包裹接口
     * @author quyang
     * @again quyang 2017-1-19
     * @update 2016-11-24
     */
    public function rejectPacket(){
        $data = I('param.');
        if(empty($data['stationId']) || empty($data['content']) || empty($data['packetId'])){
            $this->param_error();
        }
        $parcelService = new \Home\Server\QueryParcelService();
        $arr = $parcelService->RejectParcel($data);
        if($arr === false){
            $this->output(0);
        }
        //包裹提货时判断队列表包裹发送状态。如果不是成功则改为发送成功  12-30
        //批量拒收  17-2-27
        $parcelId = explode(',',$data['packetId']);

        foreach ( $parcelId as $v ){
            $Notice = new \Home\Server\ParcelNoticeResultServer();
            $res = $Notice->queryParcelNotice( $v );

            if ($res['f_sms_notice'] != '1' && $res['f_weixin_notice'] != '1'){
                $Notice->updateParcelNotice( $v , ['f_sms_notice'=>'1'] , $res['table_name'] );
            }

            //快递对接
            $parceNoticeResult = new \Home\Model\StationAbutmentLogModel();

            $totalRow['f_parcel_id'] = $v;

            //查询快递队列表是否存在该数据
            $list = $parceNoticeResult->where($totalRow)->field('f_id')->find();

            if ($list){

                $totalRow['f_storage_status'] ='1';

                $parcel_info = $parceNoticeResult->queryParcelData($totalRow);
                if (!empty($parcel_info)){
                    $express_where = array('f_type'=>'3','f_create_time'=>date('YmdHis'),'f_common'=>$data['content']);
                    $parceNoticeResult->updateExpressData($v,$express_where);
                }
            }
            
            //第三方站点对接
            $partnerNoticeResult = new \Home\Model\StationPartnerLogModel();
            $partnerRow['f_parcel_id'] = $v;
            //查询快递队列表是否存在该数据
            $plist = $partnerNoticeResult->where($partnerRow)->field('f_id')->find();
            if ($plist){
                $partnerRow['f_partner_storage_status'] ='1';
                $partner_info = $partnerNoticeResult->queryParcelData($partnerRow);
                if (!empty($partner_info)){
                    $partner_where = array('f_type'=>'3','f_create_time'=>date('YmdHis'),'f_common'=>$data['content']);
                    $partnerNoticeResult->updateExpressData($v,$partner_where);
                }
            }
        }

        $this->output(1 ,array(),'已拒收');
    }
    
    /**
     * @desc: 根据手机号，运单号或者提货吗查询包裹
     * @Author: quyang
     * @again quyang 2017-1-21
     * @update: 2016-11-22
     **/
    public function QueryOrderByCombinedNo(){
        $data=I('param.');
        if(empty($data['combinedNo']) || empty($data['stationId'])){
            $this->param_error();
        }
        $parcelService = new \Home\Server\ParcelService();
        $arr = $parcelService->getStorageList($data['stationId'],$data['combinedNo']);
        if(empty($arr)){
            $this->output(true,array());
        }
        //数组重组
        $queryinfo=array_values($arr);
        $this->output(1,$queryinfo);
    }


    /**
     * @desc: 根据手机号，运单号或者提货码查询包裹（查询运单号联系人下的所有包裹）
     * @Author: 徐庶
     * @update: 2017-07-11
     **/
    public function QueryOrderByCombinedNoBeta()
    {
        $data=I('param.');
        if(empty($data['combinedNo']) || empty($data['stationId'])){
            $this->param_error();
        }

        // 获取可用的包裹列表
        $parcelService = new \Home\Server\ParcelService();
        $arr = $parcelService->getStorageListBeta($data['stationId'],$data['combinedNo']);

        // 包裹id
        $parcelId = '';

        if(empty($arr))
        {
            $this->output(true,array());
        }
        else
        {
            // 获取所有的包裹id
            foreach ($arr as $akey => $aval)
            {
                $parcelId .= $aval['packageId'].',';
            }

            $parcelId = substr($parcelId,0,strlen($parcelId) - 1);

        }

        $parcelResultService = new \Home\Server\ParcelNoticeResultServer();

        // 根据包裹id获取对应的通知信息
        $noticeArr = $parcelResultService -> sendParcelNotice($parcelId);

        // 判断是否是运单号
        if (preg_match("/^[\w]{8,24}$/" ,$data['combinedNo']))
        {
            $flag = true;
        }

        // 判断每一个包裹的微信与短信发送状态
        foreach ($arr as $k => $v)
        {
            foreach ($noticeArr as $nkey => $nval)
            {
                if ($v['packageId'] == $nval['f_parcel_id'])
                {
                    // 判断微信发送状态
                    if ($nval['f_weixin_notice'] == 1)
                    {
                        $arr[$k]['weixin_status'] = 1 ;
                    }
                    else
                    {
                        $arr[$k]['weixin_status'] = 0 ;
                    }

                    // 判断短信发送状态
                    if ($nval['f_sms_notice'] == 1)
                    {
                        $arr[$k]['sms_status'] = 1 ;
                    }
                    else
                    {
                        $arr[$k]['sms_status'] = 0 ;
                    }
                }
            }


            // 输入的包裹编号对应的包裹，排列在第一个
            if ($flag && $v['mailNo'] == $data['combinedNo'])
            {
                array_unshift( $arr, $arr[$k]);
                unset($arr[$k + 1]);
            }

        }

        //数组重组
        $queryinfo=array_values($arr);
        $this->output(1,$queryinfo);
    }

    /**
     * @desc: 根据运单号查询包裹(两个月)
     * @Author: xushu
     * @again xushu 2017-7-7
     * @update: 2017-7-7
     **/
    public function QueryOrderByMailNo(){
        $data = I('param.');

        if (empty($data['mailNo']) || empty($data['stationId']))
        {
            $this->param_error();
        }

        // 查询站点下的包裹
        $parcelService = new \Home\Server\ParcelService();
        $arr = $parcelService->getStorageListByMailNo($data['stationId'],$data['mailNo']);

        if(empty($arr)){
            $this->output(true,array());
        }

        //数组重组
        $queryinfo=array_values($arr);
        $this->output(1,$queryinfo);

    }

    /**
     * @desc 提货接口(带批量)接口
     * @author quyang
     * @again 2017-1-19
     * @update 2016-11-24
     */
    public function pickPacket(){
        $data = I('param.');

        // ios 且 版本号低于42，不做takeCode 与 superPwd 验证 （修补ios漏洞）
        if ($_GET['bmxSource'] == 'ios' && $_GET['buildVersion'] < 42)
        {
            if(empty($data['packetIds']) || empty($data['stationId'])  || empty($data['mobile']))
            {
                $this->param_error();
            }
        }
        else
        {
            if(empty($data['packetIds']) || empty($data['stationId']) || ( ! isset( $data['takeCode'] ) && ! isset( $data['superPwd'] ) ) || empty($data['mobile'])){
                $this->param_error();
            }
        }


        //去掉多余,
        $data['packetIds'] = substr( $data['packetIds'], -1 ) == ',' ? substr( $data['packetIds'], 0, -1 ) : $data['packetIds'];

        $str = explode(',', $data['packetIds']);

        // ios 且 版本号低于42， 默认使用 “专业版出库”方式（修补ios漏洞）
        if ($_GET['bmxSource'] == 'ios'  && $_GET['buildVersion'] < 42 )
        {
            $out_source = 7;
            $useSuperPwd = true;
            $data['takeCode'] = '11111';
        }
        else
        {
            //超级密码提货  2017年3月21日 黄盖
            $useSuperPwd = isset( $data['superPwd'] ) && ! empty( trim( $data['superPwd'] ) ) ? ( new \Home\Server\UserService() ) ->verify_superPwd( $data['stationId'], $data['superPwd'] ) : False;

            //如果提货码未填, 且超级密码无效, 则直接返回错误
            if( empty( $data['takeCode'] ) && ! $useSuperPwd )
            {
                $this->auto_error('请输入正确的超级密码!');
            }

            //默认是使用提货码提货
            $out_source = 1;

            //如果使用的是超级密码提货, 记录提货方式是超级密码提货
            if( $useSuperPwd )
            {
                $out_source = 6;
            }

            //如果未使用 超级密码,  则判断用户是否是专业版, 如果是专业版, 此处就当做使用超级密码(免提货码) 提货
            if( ! $useSuperPwd )
            {
                $useSuperPwd = ( new \Home\Server\UserService() ) ->verify_professional( $data['stationId'] );

                //如果使用的是专业版提货, 记录提货方式是专业版提货  ( $useSuperPwd为false, 则说明没使用 超级密码)
                if( $useSuperPwd )
                {
                    $out_source = 7;
                }
            }
        }

        $parcelService = new \Home\Server\ParcelService();

        //出库平台  0 未知  1 IOS  2 Andoird  3 PC  5 微信
        $out_way = ( new \Home\Server\UserService() ) ->getPlatform( $data['bmxSource'], True );

        /**
         * 提货操作
         * $useSuperPwd     为true则不验证提货码
         * $out_way         出库平台  0 未知  1 IOS  2 Andoird  3 PC  5 微信
         * $out_source      出库方式  1 提货码  6 超级密码  7 专业版  8 微信扫码
         */
        $arr = $parcelService ->pickUp( $data['stationId'],$data['mobile'],$data['takeCode'],$data['packetIds'], $useSuperPwd, $out_way, $out_source );

        if($arr == false)
        {
            $this->output(0);
        }

        //包裹提货时判断队列表包裹发送状态。如果不是成功则改为发送成功  12-30
        foreach ($str as $k => $v) {
            $Notice = new \Home\Server\ParcelNoticeResultServer();
            $res = $Notice->queryParcelNotice( $v );

            //包裹状态不为发送成功则改为成功
            if ($res['f_sms_notice'] != '1' && $res['f_weixin_notice'] != '1'){
                $Notice->updateParcelNotice( $v , ['f_sms_notice'=>'1'] , $res['table_name'] );
            }

            //快递对接
            $parceNoticeResult = new \Home\Model\StationAbutmentLogModel();

            //快递对接优化  2017-05-24
            $totalRow['f_parcel_id'] = $v;
            $totalRow['f_type'] = '1';
            $totalRow['f_storage_status'] = '1';

            //查询快递队列表是否存在该数据
            $list = $parceNoticeResult->where($totalRow)->field('f_id')->find();

            if ($list){
                $express_where = array('f_type'=>'2','f_create_time'=>date('YmdHis'));
                $parceNoticeResult->updateExpressData($v,$express_where);
            }
            
            //第三方站点对接
            $partnerNoticeResult = new \Home\Model\StationPartnerLogModel();
            //快递对接优化  2017-05-24
            $partnerRow['f_parcel_id'] = $v;
            $partnerRow['f_type'] = '1';
            $partnerRow['f_partner_storage_status'] = '1';
            //查询快递队列表是否存在该数据
            $plist = $partnerNoticeResult->where($partnerRow)->field('f_id')->find();
            if ($plist){
                $partner_where = array('f_type'=>'2','f_create_time'=>date('YmdHis'));
                $partnerNoticeResult->updateExpressData($v, $partner_where);
            }
        }
        $this->output(1 ,array() ,'出库成功');
    }

    /**
     * @Desc  : 拒收件出库
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/2 16:27
     * @Update：2017/5/2
     **/
    public function outRejectParcel()
    {

        $param = I('param.');

        if( empty( $param['stationId'] ) || empty( $param['content'] ) || empty( $param['packetId'] ) )
        {
            $this->param_error();
        }

        //去掉多余,
        $param['packetId'] = substr( $param['packetId'], -1 ) == ',' ? substr( $param['packetId'], 0, -1 ) : $param['packetId'];

        $Parcel = new \Home\Server\QueryParcelService();
        //更新包裹状态
        $data = $Parcel->outRejectParcel( $param['stationId'] , $param['packetId'] , $param['content'] , 6 , $param['tableName'] );

        if ( $data == false )
        {
            $this->output( false );
        }
        //德邦的包裹需要记录以便对接
        $map = "`f_station_id` = {$param['stationId']} AND `f_parcel_id` in (".$param['packetId'].") AND `f_com_id` = 182";
        D('Home/StationAbutmentLog')->where($map)->save(['f_type' => 4, 'f_common' => $param['content']]);

        $this->output( true );

    }
    
}